package com.pinganfu.mock.server;



import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;

import org.json.JSONObject;
import org.json.XML;

/**
 * 
 * @author lijiaxiang059
 *
 */

public class ChatServer {
	BufferedWriter buffWri=null;  
  boolean started = false;
  ServerSocket ss = null;
  List<Client> clients = new ArrayList<Client>();

  public static void main(String[] args) {
    new ChatServer().start();
  }

  public void start() {
    try {
      ss = new ServerSocket(8082);
      started = true;
      System.out.println("端口已开启,占用8081端口号....");
    } catch (BindException e) {
      System.out.println("端口使用中......");
      System.out.println("请关掉相关程序并重新运行服务器！");
      System.exit(0);
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      while (started) {
        Socket s = ss.accept();
        Client c = new Client(s);
        System.out.println("--------------一个客户端接入-------------");
        new Thread(c).start();
        clients.add(c);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        ss.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  class Client implements Runnable {
    private Socket s;
    private DataInputStream dis = null;
    private DataOutputStream dos = null;
    private boolean bConnected = false;

    public Client(Socket s) {
      this.s = s;
      try {
        dis = new DataInputStream(s.getInputStream());
        dos = new DataOutputStream(s.getOutputStream());
        bConnected = true;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    public void send(String str) {
      try {
        dos.writeUTF(str);
      } catch (IOException e) {
        clients.remove(this);
        System.out.println("对方退出了！我从List里面去掉了！");
      }
    }

    public void run() {
      try {
        while (bConnected) {
          String response ="";
        	
          String str = dis.readUTF();
          //System.out.println("------------来自本地服务器:" + str);
          //String testString = "这个数据是服务器返回的："+str;
          
          SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  		  String request_time = df.format(new Date());
  		
          System.out.println(request_time +"\t服务器端得到数据：" + str.toString());
          
          String fileName2="json.xml";    
          buffWri=new BufferedWriter(new FileWriter(fileName2));
          JSONObject jsonObj=new JSONObject(str);  
          buffWri.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
          buffWri.write("<ROOT>");
          buffWri.write(XML.toString(jsonObj));
          buffWri.write("</ROOT>");    
          buffWri.flush();    
          
          final RandomAccessFile randomFile = new RandomAccessFile(fileName2,"rw");
          String tmp = "";     
          while( (tmp = randomFile.readLine())!= null) {     
        	  response =response+"\n"+ new String(tmp.getBytes("ISO8859-1"));     
          } 
          
          for (int i = 0; i < clients.size(); i++) {
            Client c = clients.get(i);
            c.send(response);
          }
        }
      } catch (EOFException e) {
        System.out.println("Client closed!");
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          if (dis != null)
            dis.close();
          if (dos != null)
            dos.close();
          if (s != null) {
            s.close();
          }

        } catch (IOException e1) {
          e1.printStackTrace();
        }

      }
    }
  }
}

